﻿using HslCommunication.Profinet.Omron;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace paraInterface
{
    internal class omronPLCTemper:PLC
    {

        OmronFinsUdp omronPLC { get; set; }
        Dictionary<string, string> dict = new Dictionary<string, string>();

        public override bool InitPLC()
        {
            if (IsIP(IP))
            {
                omronPLC = new OmronFinsUdp(IP, 9600);
                omronPLC.DNA = 0;
                omronPLC.DA1 = 0;
                omronPLC.SNA = 0;
                omronPLC.SA1 = (byte)SUB;
                isRealPLC = true;
            }
            return isRealPLC;
        }
        public override bool SendData2PLC(jsonData data)//需要将数据进行解析
        {
            int MAXCOUNT = 30;
            if (data.PARAMS.Length < MAXCOUNT)
                return false;

            int[] _Index=new int[30] { 
                0,1,2,3,20,21,
                4,5,6,7,22,23,
                8,9,10,11,24,25,
                12,13,14,15,26,27,
                16,17,18,19,28,29
            };

            for (int i = 0; i < data.PARAMS.Length; i++)
            {
                dict[data.PARAMS[i].TBGD_ITEM_CODE] = data.PARAMS[i].TBGD_UPPER_LIMIT.Trim();
                if (dict[data.PARAMS[i].TBGD_ITEM_CODE].Length == 0) dict[data.PARAMS[i].TBGD_ITEM_CODE] = "0";
            }
            short[] v = new short[MAXCOUNT+1];
            string s;
            for (int i = 0; i < MAXCOUNT; i++)//暂定的规则
            {
                s = $"T{(i+1).ToString().PadLeft(3, '0')}";
                if (dict.ContainsKey(s) && short.TryParse(dict[s], out short x))
                    v[_Index[i]] = x;
            }
            v[30] = 1;
            return WriteWords(ADD, v);
        }

        private bool WriteWords(string sStartAdd, short[] sValue)
        {
            OperateResult res = omronPLC.Write(sStartAdd, sValue);
            if (res.IsSuccess)
                pubcls.WriteLog("数据写入成功\n数据:" + sValue.ToJsonString());
            else
                pubcls.WriteLog("数据写入失败\n数据:" + sValue.ToJsonString());
            return res.IsSuccess;
        }

    }
}
